package com.stuffthathappens.concurrency;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import java.util.concurrent.locks.Lock;
import java.util.Map;
import java.util.HashMap;

/**
 * This demonstrates how to use ReadWriteLock for a read-mostly data structure.
 *
 * @author Eric Burke
 */
public class NameIdLookup {
    private final ReadWriteLock rwl = new ReentrantReadWriteLock();
    private final Lock r = rwl.readLock();
    private final Lock w = rwl.writeLock();

    private final Map<Integer, String> idToName = new HashMap<Integer, String>();
    private final Map<String, Integer> nameToId = new HashMap<String, Integer>();


    public Integer getId(String name) {
        r.lock();
        try {
            return nameToId.get(name);
        } finally {
            r.unlock();
        }
    }

    public String getName(Integer id) {
        r.lock();
        try {
            return idToName.get(id);
        } finally {
            r.unlock();
        }
    }

    public void put(Integer id, String name) {
        w.lock();
        try {
            idToName.put(id, name);
            nameToId.put(name, id);
        } finally {
            w.unlock();
        }
    }
}
